package com.ding.dailyup.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ding.dailyup.entity.UserInfoEntity;
import com.ding.dailyup.model.UserInfo;
import com.ding.dailyup.entity.request.WxLoginReq;
import com.ding.dailyup.entity.response.UserLoginResp;
import com.ding.dailyup.service.UserService;
import com.ding.dailyup.entity.JsonResult;
import com.ding.dailyup.exception.ParamException;
import com.ding.dailyup.util.IpUtil;
import com.ding.dailyup.util.UserTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/wx/auth")
@Api(tags = "微信授权")
@Slf4j
public class WxAuthController {

	@Autowired
	private UserService userService;

	@PostMapping("/login")
	@ApiOperation(value = "微信登录")
	public JsonResult<UserLoginResp> loginByWx(
			@RequestBody WxLoginReq wxLoginInfo, HttpServletRequest request) {
		String code = wxLoginInfo.getCode();
		UserInfoEntity userInfoEntity = wxLoginInfo.getUserInfo();
		if (StrUtil.isEmpty(code) || ObjectUtil.isNull(userInfoEntity)) {
			throw new ParamException("参数异常");
		}
		UserInfo user = userService.saveWxUser(wxLoginInfo.getCode(),
				IpUtil.getIpAddr(request), wxLoginInfo.getUserInfo());
		String token = UserTokenUtil.generateToken(user.getId().intValue());

		UserLoginResp userLoginResp = new UserLoginResp();
		BeanUtil.copyProperties(user, userLoginResp,
				CopyOptions.create().ignoreNullValue());
		userLoginResp.setToken(token);
		return JsonResult.succResult(userLoginResp);
	}

	@PostMapping("/logout")
	@ApiOperation(value = "微信登出")
	public JsonResult loginByWx() {
		return JsonResult.succResult();
	}
}
